
(function() {

    // Global vars
    var selection = '';

    // XUL elements
    var elements = {};

    // Context menu
    var contextMenu;

    // On window load
    window.addEventListener("load", function() {

        contextMenu = UtilChrome.gid("contentAreaContextMenu") || UtilChrome.gid("mailContext");

        // XUL elements
        elements["sendtoserver"] = document.getElementById("sendtoserver");

        // Events
        initEvents();

    }, false);

    function initEvents() {

        // Right click
        contextMenu.addEventListener("popupshowing", onGtransPopup, false);

        // On Command of sendtoserver
        elements["sendtoserver"].addEventListener("command", onSendToServer, false);

    }
    
    // On right click event
    function onGtransPopup(event) {

        if (event.target !== contextMenu)  {
            return;
        }

        var popupnode = document.popupNode;

        // Get and trim current selection
        selection = getSelection(popupnode);
    }

    function onSendToServer() {
	var params = {inn:{selection:selection}, out:null}; 
	window.openDialog('chrome://hackernerd/content/search.xul',
			  '',
			  'chrome,centerscreen,modal, resizable=yes, titlebar=0, width=420,height=230',
			  params);
   }

    function getSelection(popupnode) {

        var nodeLocalName = popupnode.localName.toLowerCase();
        var selection = '';

        // Input or textarea ?
        if ((nodeLocalName == "textarea") || (nodeLocalName == "input" && popupnode.type == "text")) {

            selection = popupnode.value.substring(popupnode.selectionStart, popupnode.selectionEnd);

        // Image ?
        } else if (nodeLocalName == "img") {

            // Image title ?
            if (popupnode.title) {
                selection = popupnode.title;

            // Image alternative ?
            } else if (popupnode.alt) {
                selection = popupnode.alt;
            }

        // Link ?
        } else if (nodeLocalName == "a" && popupnode.hasAttribute("href") && (popupnode.textContent != "" || popupnode.hasAttribute("title"))) {

            // Link content ?
            if (popupnode.textContent != "") {
                selection = popupnode.textContent;

            // Link title ?
            } else if (popupnode.hasAttribute("title")) {
                selection = popupnode.getAttribute("title");
            }

        // Text selection.
        } else {
            selection = document.commandDispatcher.focusedWindow.getSelection().toString();
        }

        return selection;
    }

})();
